package huoye.shops.huoye.user.activity;

import android.Manifest;
import android.content.Context;
import android.content.res.AssetManager;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.TextView;

import com.codeideology.android.utils.AssetUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import huoye.shops.R;
import huoye.shops.base.APIUrls;
import huoye.shops.base.BaseActivity;
import huoye.shops.base.UserManager;
import huoye.shops.huoye.user.model.AreaInfo;
import huoye.shops.huoye.user.model.Province;
import huoye.shops.huoye.user.model.SelectCityData;
import huoye.shops.huoye.user.presenter.SelectCityPresenter;
import huoye.shops.huoye.user.view.ISelectCityView;
import pub.devrel.easypermissions.EasyPermissions;

public class SelectNewActivity extends BaseActivity implements ISelectCityView, EasyPermissions.PermissionCallbacks {

    @BindView(R.id.sp_province)
    Spinner spProvince;
    @BindView(R.id.sp_city)
    Spinner  spCity;
    @BindView(R.id.sp_area)
    Spinner  spArea;
    @BindView(R.id.tv_select_city)
    TextView tvSelectCity;
    private SelectCityPresenter mSelectCityPresenter;

    @OnClick(R.id.btn_ok)
    void onOkClick(){
        mSelectCityPresenter.selectCity(provinceName,cityName,areaName);
    }


    private ArrayAdapter<String> cityAdapter;
    private ArrayAdapter<String> areaAdapter;



    private List<String> provinceList = new ArrayList<>(); // 所有省份的list
    private List<String> cityList = new ArrayList<>();     // 当前选中省份的城市
    private List<String> areaList = new ArrayList<>();     // 当前选中城市的城区

    private String provinceName;    // 省的名字
    private String cityName;        // 市的名字
    private String areaName;        // 区的名字

    private int provincePosition = 0; // 当前选的省份的位置
    private int cityPosition = 0;     // 当前城市在List中的位置
    private int areaPosition = 0;     // 当前城区在list的位置

    @Override
    protected int getContentViewId() {
        return R.layout.activity_select_city;
    }

    @Override
    protected void initView(@Nullable Bundle bundle) {

        mSelectCityPresenter = new SelectCityPresenter();
        mSelectCityPresenter.addTaskListener(this);
        mSelectCityPresenter.onStart();

        mSelectCityPresenter.getAreaInfo(ftype,"");

        showCityData();
        showAreaData();
        openPower();
    }


    private String ftype = "0";

    @Override
    public void getAreaData(List<AreaInfo> list) {
        switch (ftype){
            case "0":
                for (int i = 0 ; i < list.size();i++){
                    provinceList.add(list.get(i).getSname());
                }
                showProvinceData();
                break;
            case "1":
                cityList.clear();
                for (int i = 0 ; i < list.size();i++){
                    cityList.add(list.get(i).getSname());
                }
                // 刷新城市列表
                spCity.setSelection(0);
                cityName = cityList.get(0);
                cityAdapter.notifyDataSetChanged();
            case "2":
                areaList.clear();
                for (int i = 0 ; i < list.size();i++){
                    areaList.add(list.get(i).getSname());
                }
                // 刷新城市列表
                spArea.setSelection(0);
                areaName = areaList.get(0);
                areaAdapter.notifyDataSetChanged();
                break;
        }
    }




    /**
     * 展示数据
     */
    private void  showProvinceData() {
        // 显示省份数据
        spProvince.setAdapter(new ArrayAdapter<String>(this, R.layout.support_simple_spinner_dropdown_item, provinceList));
        spProvince.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                provincePosition = position;
                provinceName = provinceList.get(position);
                // 获取当前省份对应的城市list

                ftype = "1";
                mSelectCityPresenter.getAreaInfo("1",provinceName);

                // 刷新城区列表
              //  updateArea(0);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });



    }


    private void showCityData(){
        // 显示城市数据
        spCity.setAdapter(cityAdapter = new ArrayAdapter<String>(this,R.layout.support_simple_spinner_dropdown_item, cityList));
        spCity.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                cityPosition = position;
                cityName = cityList.get(position);
                ftype = "2";
                mSelectCityPresenter.getAreaInfo("2",cityName);
                // 刷新城区列表
                updateArea(position);

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    private void showAreaData(){
        // 显示城区数据
        spArea.setAdapter(areaAdapter = new ArrayAdapter<String>(this, R.layout.support_simple_spinner_dropdown_item, areaList));
        spArea.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                areaName = areaList.get(position);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }






    /**
     * 更新城区数据
     *
     * @param position
     */
    private void updateArea(int position) {
  /*      areaList.clear();
        Province.CityBean cityBean = provinces.get(provincePosition).getCity().get(position);
        areaList.addAll(cityBean.getArea());
        spArea.setSelection(0);
        areaName = areaList.get(0);
        areaAdapter.notifyDataSetChanged();*/
    }





    @Override
    public void getUrl(SelectCityData selectCityData) {
        tvSelectCity.setText((provinceName.equals(cityName) ? "" : provinceName+" ") + cityName +" "+ areaName);
        String s = tvSelectCity.getText().toString();
        UserManager.getInstance().saveCity(s);
        UserManager.getInstance().saveUrl(selectCityData.getApiUrl());
        UserManager.getInstance().saveImageUrl(selectCityData.getOssUrl());
        startActivity(LoginActivity.class);
    }








    //打开定位和存储权限
    private void openPower(){
        String[] perms = {Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.CAMERA};
        if (EasyPermissions.hasPermissions(this, perms)) {

            // 已经申请过权限，做想做的事
        } else {
            // 没有申请过权限，现在去申请
            EasyPermissions.requestPermissions(this, "打开定位,相机，存储权限",
                    APIUrls.COMMON_CONFIG.PERMISSIONS_CODE, perms);
        }

    }



    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {

    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        //无权限，且被选择"不再提醒"：提醒客户到APP应用设置中打开权限
        if (!ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) {
            makeToast("拒绝权限，不再弹出询问框，请前往APP应用设置中打开此权限");
        } else {//无权限，只是单纯被拒绝
            makeToast( "拒绝权限，等待下次询问哦");
        }
    }
}
